package com.tianzehua.netty.httpexample;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;
import java.net.URISyntaxException;


/**
 * @author Administrator
 */
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    final  String ICO = "/favicon.ico";

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws URISyntaxException {
        /* channelRead0 这个方法的意思就是读取客户端发来的消息，并且返回相应到客户端的方法 Inbound 进来的请求，outbound 出去的请求*/
        /* 获取远程请求的地址和端口号等相关信息 */
        System.out.println(ctx.channel().remoteAddress());

        if (msg instanceof  HttpRequest){
            HttpRequest request = (HttpRequest) msg;

            System.out.println("请求的方法名："+ request.method().name());

            URI uri =new URI(request.uri());
            if (ICO.equals(uri.getPath())){
                System.out.println("请求favicon.ico");
                return;
            }

            /* 返回的字符 */
            ByteBuf content = Unpooled.copiedBuffer("Hello Word", CharsetUtil.UTF_8);
            /* 构造返回对象HTTP相应 */
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK,content);
            /* 设置返回的response的头信息 */
            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());

            /* 写到缓存区并且返回到客户端中 */
            ctx.writeAndFlush(response);
            /* 关闭连接 */
            ctx.channel().close();
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel active");
        super.channelActive(ctx);
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel registered");
        super.channelRegistered(ctx);
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handler added");
        super.handlerAdded(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel inactive");
        super.channelInactive(ctx);
    }
}
